package com.example.demo;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SecureRandom;

public class RSASHA256Example {
    public static void main(String[] args) {
        try {
            // 生成RSA密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            // 获取Signature实例
            Signature signature = Signature.getInstance("SHA256withRSA");

            // 使用私钥初始化签名
            signature.initSign(privateKey);

            String message = "This is a secure message.";
            byte[] messageBytes = message.getBytes();

            // 添加数据到签名
            signature.update(messageBytes);

            // 签名数据
            byte[] digitalSignature = signature.sign();
            System.out.println("Signature: " + bytesToHex(digitalSignature));

            // 使用公钥初始化验证
            signature.initVerify(publicKey);

            // 再次添加相同的数据
            signature.update(messageBytes);

            // 验证签名
            boolean verified = signature.verify(digitalSignature);
            System.out.println("Signature verified: " + verified);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 辅助方法，用于将字节转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02x", b));
        }
        return builder.toString();
    }
}
